const textBounce = (title, pageTxt, callBack1, callBack2) => {
	var timer = null;
	if (null != timer) {
		clearInterval(timer);
	}
	var showText = '';
	var i = 0;
	timer = setInterval(function() {
		showText = pageTxt.substring(0, i);
		callBack1(showText.replace(new RegExp(title), '<span style="color: rgba(208, 57, 86, 1);">' +
			title + '</span>'));
		i++;
		if (showText == pageTxt) {
			clearInterval(timer)
			callBack2();
		};
	}, 30);
}
// 倒计时
const countDownTime = (expiryDate, countDownEnd) => {
	var expDate = expiryDate;
	var nowDate = new Date().getTime();
	var cdDate = new Date(expDate - nowDate);
	if (cdDate > 0) {
		var days = parseInt(cdDate / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
		var hours = parseInt(cdDate / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
		var minutes = parseInt(cdDate / 1000 / 60 % 60, 10); //计算剩余的分钟 
		var seconds = parseInt(cdDate / 1000 % 60, 10); //计算剩余的秒数
		days = checkTime(days);
		hours = checkTime(hours);
		minutes = checkTime(minutes);
		seconds = checkTime(seconds);
		countDownEnd(days + ":" + hours + ":" + minutes + ":" + seconds);
	} else {
		countDownEnd("00:00:00:00");
	}

	var timer = setInterval(() => {
		var nowDate = new Date().getTime();
		var cdDate = new Date(expDate - nowDate);
		if (cdDate > 0) {
			var days = parseInt(cdDate / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
			var hours = parseInt(cdDate / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 
			var minutes = parseInt(cdDate / 1000 / 60 % 60, 10); //计算剩余的分钟 
			var seconds = parseInt(cdDate / 1000 % 60, 10); //计算剩余的秒数

			days = checkTime(days);
			hours = checkTime(hours);
			minutes = checkTime(minutes);
			seconds = checkTime(seconds);
			countDownEnd(days + ":" + hours + ":" + minutes + ":" + seconds);
			cdDate -= 1000;
		} else {
			countDownEnd("00:00:00:00");
			clearInterval(timer);
		}
	}, 1000)
}
//将0-9的数字前面加上0，例1变为01 
const checkTime = (i) => {
	if (i < 10) {
		i = "0" + i;
	}
	return i.toString();
}

// 示例
// const result = splitString("123abc");
// console.log(result); // { numbers: '123', text: 'abc' }
function splitString(str) {
	const match = str.match(/^(\d+)(.*)/);
	if (match) {
		return {
			numbers: match[1],
			text: match[2]
		};
	} else {
		return {
			numbers: '',
			text: str
		};
	}
}

// 数字转大写字母
const numToCode = (num) => {
	return String.fromCharCode(num + 65)
}
const countDownSecond = (seconds, countDownSecondEnd) => {
	var secondTimer = setInterval(() => {
		seconds--
		countDownSecondEnd(seconds);
		if (seconds == 0) {
			clearInterval(secondTimer);
		}
	}, 1000)
}
const showToast = (toastText) => {
	uni.showToast({
		icon: 'none',
		title: toastText,
	})
}
const stringFormat = (formatted, args) => {
	for (let i = 0; i < args.length; i++) {
		let regexp = new RegExp('\\{' + i + '\\}', 'gi')
		formatted = formatted.replace(regexp, args[i])
	}
	return formatted
}

function toQueryString(obj) {
	const keyValuePairs = [];
	for (const key in obj) {
		if (obj.hasOwnProperty(key)) {
			keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
		}
	}
	return '?' + keyValuePairs.join('&');
}
const contactOurs = () => {
	uni.makePhoneCall({
		phoneNumber: '15317081169' //联系客服
	})
}

function shuffleArray(array) {
	// 创建一个副本以避免修改原数组
	let shuffledArray = array.slice();

	// 使用 Fisher-Yates 洗牌算法打乱数组
	for (let i = shuffledArray.length - 1; i > 0; i--) {
		const j = Math.floor(Math.random() * (i + 1));
		[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
	}

	return shuffledArray;
}

const getViewPostion = (selector) => {
	return new Promise((resolve) => {
		//uni.createSelectorQuery() 查询节点信息的对象   select选择要操作那个 
		let view = uni.createSelectorQuery().select(selector);
		//fields 配置查询节点信息对象的内容都有那些 
		view.fields({
				size: true, //是否返回节点尺寸
				rect: true, //是否返回节点布局位置
				scrollOffset: true //是否返回节点的 scrollLeft scrollTop，节点必须是 scroll-view 或者 viewport
			},
			(res) => { //  res 是返回 所需的信息对象
				resolve(res);
			}).exec(); //exec 执行所有的请求
	})
}

Date.prototype.format = function(format) {
	var date = {
		"M+": this.getMonth() + 1,
		"d+": this.getDate(),
		"h+": this.getHours(),
		"m+": this.getMinutes(),
		"s+": this.getSeconds(),
		"q+": Math.floor((this.getMonth() + 3) / 3),
		"S+": this.getMilliseconds()
	};
	if (/(y+)/i.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for (var k in date) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
				date[k] : ("00" + date[k]).substr(("" + date[k]).length));
		}
	}
	return format;
}
// 用以清除对象空属性
const removeEmptyProperty = (obj) => {
	Object.keys(obj).forEach(item => {
		if (obj[item] === '' || obj[item] === undefined || obj[item] === null || obj[item] === 'null')
			delete obj[item]
	})
	return obj
}
const formatDate = (date) => {
	//date = new Date(Date.parse()); //转换成Data();
	var y = date.getFullYear();
	var m = date.getMonth() + 1;
	m = m < 10 ? '0' + m : m;
	var d = date.getDate();
	d = d < 10 ? ('0' + d) : d;
	return y + '-' + m + '-' + d;
}

function parseKeyValueString(str) {
	const pairs = str.split('@');
	const result = {};
	pairs.forEach(pair => {
		const parts = pair.split('=');
		result[parts[0]] = parts[1];
	});
	return result;
}

const showErrorModal = (text) => {
	uni.showModal({
		showCancel: false,
		content: text,
		success: function(res) {
			uni.redirectTo({
				url: '/pages/sclList/sclList'
			})
		}
	})
}

const getPhoneNumberXingHao = (text) => {
	if (undefined != text && null != text && '' != text) {
		var arry = text.split("");
		var phoneNumberXingHao = '';
		arry.forEach(function(item, index) {
			if (index >= 3 && index <= 7) {
				phoneNumberXingHao += '*';
			} else {
				phoneNumberXingHao += item;
			}
		})
		return phoneNumberXingHao;
	}
}


const isJSON = (str) => {
	try {
		JSON.parse(str);
		return true;
	} catch (error) {
		return false;
	}
}
var fangBaoTime = 0;
const fangBaoClick = (time=1500) => {
	if (new Date().getTime() - fangBaoTime < time) { //防爆防抖间隔为1500
		return true //防止
	}
	fangBaoTime = new Date().getTime();
	return false //放开
}

const formatRichText = (html) => {
	// 去掉img标签里的style、width、height属性
	let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	});
	// 修改所有style里的width属性为max-width:100%
	newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
			'max-width:100%;');
		return match;
	});
	// newContent = newContent.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
	// newContent = newContent.replace(/<img[^>]*>"/gi, '');
	// 去掉<br/>标签
	newContent = newContent.replace(/<br[^>]*\/>/gi, '');
	newContent = newContent.replace(/\n/gi, '<br/>');
	// img标签添加style属性：max-width:100%;height:auto
	newContent = newContent.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	newContent = newContent.replace(/<body>/gi, '');
	newContent = newContent.replace(/<\/body>/gi, '');
	return newContent;
}

const calculateDiscountedPrice = function(originalPrice, discount) {

	if (originalPrice == 0 || discount == 10) {
		return 0
	}
	// 确保 originalPrice 和 discount 是有效的数字
	if (typeof originalPrice !== 'number' || typeof discount !== 'number' || discount < 0 || discount > 100) {
		return "Invalid input"; // 输入无效
	}

	const discountPercentage = (10 - discount) / 10;
	// console.log(discountPercentage,'---discountPercentage')
	const discountedPrice = originalPrice - (originalPrice * discountPercentage);
	// console.log(discountedPrice,'----discountedPrice')

	// 使用 toFixed 方法将结果保留两位小数
	const roundedPrice = discountedPrice.toFixed(2);
	if (roundedPrice < 0.01) {
		return 0.01
	} else {
		return parseFloat(roundedPrice); // 返回计算后的价格，作为浮点数 
	}
}


var entityMap = {
	escape: {
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;',
		'"': '&quot;',
		"'": '&apos;',
	},
	unescape: {
		'&amp;': "&",
		'&apos;': "'",
		'&gt;': ">",
		'&lt;': "<",
		'&quot;': '"',
		"<p>": "",
		"</p>": "",
		"<br>": ""
	}
};
var entityReg = {
	escape: RegExp('[' + Object.keys(entityMap.escape).join('') + ']', 'g'),
	unescape: RegExp('(' + Object.keys(entityMap.unescape).join('|') + ')', 'g')
}

let settingWritePhotosAlbum = false;
// 保存图片(本地图，如canvas生成的本地图片)
const saveLocalImg = function(url, callback) {
	if (url) {
		// #ifdef MP-WEIXIN
		if (settingWritePhotosAlbum) {
			uni.getSetting({
				success: res => {
					if (res.authSetting['scope.writePhotosAlbum']) {
						uni.showLoading({
							title: '正在下载'
						});
						uni.saveImageToPhotosAlbum({
							filePath: url,
							success: () => {
								uni.hideLoading();
								callback && callback('success');
								uni.showToast({
									title: '保存成功'
								});
							},
							fail(e) {
								uni.hideLoading();
								// tip({
								// 	title: '下载失败，错误原因：' + e
								// 		.errMsg,
								// 	icon: "none"
								// });
								callback && callback("下载失败，错误原因:" + e.errMsg);
							}
						});
					} else {
						uni.showModal({
							title: '提示',
							content: '请先在设置页面打开“保存相册”使用权限',
							confirmText: '去设置',
							cancelText: '算了',
							success: data => {
								if (data.confirm) {
									uni.openSetting({
										success(settingdata) {
											if (settingdata.authSetting[
													'scope.writePhotosAlbum']) {
												uni.showModal({
													title: '提示',
													content: '获取权限成功,再次保存图片即可成功',
													showCancel: false,
												})
											} else {
												uni.showModal({
													title: '提示',
													content: '获取权限失败，无法保存到相册',
													showCancel: false,
												})
											}

										},
										complete(complet) {
											console.log("complete", complet)
										}
									});
								}
							}
						});
					}
				}
			});
		} else {
			settingWritePhotosAlbum = true;
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success: () => {
					uni.showLoading({
						title: '正在下载'
					});
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success: () => {
							uni.hideLoading();
							callback && callback();
							uni.showToast({
								title: '保存成功'
							});
						},
						fail(e) {
							uni.hideLoading();
							tip({
								title: '下载失败，错误原因：' + e.errMsg,
								icon: "none"
							});
						}
					});
				}
			});
		}
		// #endif
		// #ifdef H5
		uni.showLoading({
			title: '正在下载'
		});
		uni.downloadFile({
			url: url,
			success: data => {
				uni.hideLoading();
				if (data.statusCode == 200) {
					callback && callback();
					window.open(data.tempFilePath);
				} else {
					uni.showToast({
						title: '下载失败',
						icon: "none"
					});
				}
			},
			fail(e) {
				uni.hideLoading();
				uni.showToast({
					title: '下载失败，错误原因：' + e.errMsg,
					icon: "none"
				});
			}
		});
		// #endif
		// #ifdef APP-PLUS
		uni.showLoading({
			title: '正在下载'
		});
		uni.saveImageToPhotosAlbum({
			filePath: url,
			success: () => {
				uni.hideLoading();
				callback && callback();
				uni.showToast({
					title: '保存成功'
				});
			},
			fail(e) {
				uni.hideLoading();
				uni.showToast({
					title: '下载失败，错误原因：' + e.errMsg,
					icon: "none"
				});
			}
		});
		// #endif
	} else {
		uni.showToast({
			title: '海报生成中，请稍等',
			icon: 'none'
		});
	}
};


// 将HTML转义为实体
function escape(html) {
	if (typeof html !== 'string') return ''
	return html.replace(entityReg.escape, function(match) {
		return entityMap.escape[match]
	})
}

// 将实体转回为HTML
function unescape(str) {
	if (typeof str !== 'string') return ''
	return str.replace(entityReg.unescape, function(match) {
		return entityMap.unescape[match]
	})
}

function clearHtmlText(html) {
	return html.replace(/<[^>]+>/g, '');
}



function parseQueryString(data) {
	// 获取问号后面的部分
	const queryString = data.split('?')[1];

	// 如果没有查询字符串，返回空对象
	if (!queryString) {
		return {};
	}

	// 将查询字符串分割成键值对
	const pairs = queryString.split('&');
	const result = {};

	// 遍历每个键值对并解析
	pairs.forEach(pair => {
		const [key, value] = pair.split('=');
		result[decodeURIComponent(key)] = decodeURIComponent(value);
	});

	return result;
}


module.exports = {
	textBounce: textBounce,
	countDownTime: countDownTime,
	numToCode: numToCode,
	countDownSecond: countDownSecond,
	showToast: showToast,
	stringFormat: stringFormat,
	contactOurs: contactOurs,
	getViewPostion: getViewPostion,
	toQueryString,
	shuffleArray,
	formatDate,
	removeEmptyProperty,
	parseKeyValueString,
	showErrorModal,
	getPhoneNumberXingHao,
	isJSON,
	fangBaoClick,
	formatRichText,
	calculateDiscountedPrice,
	splitString,
	escape,
	unescape,
	saveLocalImg,
	parseQueryString,
	clearHtmlText
}